package com.qinglei.recoup.system.task;

import com.qinglei.recoup.common.domain.CommonConstant;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.system.pojo.TourTimeVO;
import com.qinglei.recoup.system.service.TourLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 处理巡查相关定时任务
 */
@Slf4j
@Component
public class TourTask {

    @Autowired
    private RedisService redisService;

    @Resource
    private TourLogService tourLogService;
    
    public void checkTourTime() {
        log.info("checkTourTime run");
        try {
            long expire = System.currentTimeMillis() / 1000;
            // 检查已经结束的巡查时间段
            Set<String> endTourTimes = redisService.zrangeByScore(CommonConstant.TOUR_TIME_END_ZSET_PREFIX,
                    "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(endTourTimes)) {
                endTourTimes.forEach(timeStr -> {
                    try {
                        TourTimeVO tourTimeVO = JsonUtils.jsonToBean(timeStr, TourTimeVO.class);
                        tourLogService.procTourTimeEnd(tourTimeVO);
                    } catch (Exception e) {
                        log.error("checkTourTime end error", e);
                    }
                });
            }
            // 检查已经开始的巡查时间段
            Set<String> startTourTimes = redisService.zrangeByScore(CommonConstant.TOUR_TIME_START_ZSET_PREFIX,
                    "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(startTourTimes)) {
                log.info("checkTourTime found startTourTimes:{}", startTourTimes);
                startTourTimes.forEach(timeStr -> {
                    try {
                        TourTimeVO tourTimeVO = JsonUtils.jsonToBean(timeStr, TourTimeVO.class);
                        tourLogService.procTourTimeStart(tourTimeVO);
                    } catch (Exception e) {
                        log.error("checkTourTime start error", e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("checkTourTime error", e);
        }
    }
}
